import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import PublicActivities from '../views/PublicActivities.vue'
import ActivityDetail from '../views/ActivityDetail.vue'
import ActivityManagement from '../views/ActivityManagement.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities',
    name: 'PublicActivities',
    component: PublicActivities,
    meta: { requiresAuth: true }
  },
  {
    path: '/public-activities/:id',
    name: 'ActivityDetail',
    component: ActivityDetail,
    meta: { requiresAuth: true }
  },
  {
    path: '/activity-management',
    name: 'ActivityManagement',
    component: ActivityManagement,
    meta: { requiresAuth: true, requiresAdmin: true },
    beforeEnter: (to, from, next) => {
      const user = localStorage.getItem('user');
      const isAdmin = user && JSON.parse(user).role === 'admin';
      if (isAdmin) {
        next();
      } else {
        alert('无权限访问此页面');
        next('/');
      }
    }
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('user');

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next('/login');
    } else {
      if (to.matched.some(record => record.meta.requiresAdmin)) {
        const isAdmin = JSON.parse(isAuthenticated).role === 'admin';
        if (isAdmin) {
          next();
        } else {
          alert('无权限访问此页面');
          next('/');
        }
      } else {
        next();
      }
    }
  } else {
    next();
  }
})

export default router